package com.xl.web.controller.common;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.xl.base.annotation.Auth;
import com.xl.core.util.DateUtils;
import com.xl.core.util.HtmlUtil;
import com.xl.core.util.UUIDGenerator;
import com.xl.core.util.prop.SysConfig;
import com.xl.base.web.BaseController;
import com.xl.core.constant.Globals;

/**
 * 文件上传公用控制器
 * 
 * @author 梁华
 */
@Controller
@Scope("prototype")
@RequestMapping("/file")
public class FileUploadController extends BaseController {

	/**
	 * 上传单个文件
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Auth(verifyLogin = true)
	@ResponseBody
	@RequestMapping("/upload")
	public void upload() throws Exception {
		// 保存文件
		Map<String, Object> mapRet = saveFile(request);
		HtmlUtil.writerJson(response, mapRet);
	}

	/**
	 * 实际保存文件
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> saveFile(HttpServletRequest request)
			throws Exception {
		Map<String, Object> mapRet = new HashMap<String, Object>();
		// 转型为MultipartHttpRequest：
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件
		MultipartFile multipartFile = multipartRequest.getFile("files");
		// 获得文件名
		String filename = multipartFile.getOriginalFilename();

		// 重新定义文件名，防止中文名浏览器自动转义
		String newName = UUIDGenerator.generate()
				+ filename.substring(filename.indexOf(Globals.DOT),
						filename.length());

		// 获取当天的日期，防止同一文件夹文件过多，影响效率
		String today = DateUtils.formatDate("yyyyMMdd");
		// 生成文件保存路径与网络访问路径
		String physicalPath = SysConfig.fileUploadPath + Globals.BAR + today
				+ Globals.BAR + newName;
		String netUrl = SysConfig.nginxRootUrl + Globals.BAR + today
				+ Globals.BAR + newName;

		// 写入文件
		File source = new File(physicalPath.toString());
		if (!source.getParentFile().exists()) {
			source.getParentFile().mkdirs();
		}
		multipartFile.transferTo(source);
		mapRet.put("physicalPath", physicalPath);
		mapRet.put("netUrl", netUrl);

		return mapRet;
	}
}
